<template>
  <div id="playercontent">
    <div
      id="dplayer"
      @dblclick="fullScreen"
    ></div>
    <classTest
      :videoCurrentTime="videoCurrentTime"
      :duration="duration"
      ref="classTest"
    ></classTest>
  </div>
</template>

<script>
import Hls from "hls.js";
import DPlayer from "dplayer";
import classTest from "../homepage/course/openclassPlayer/class-test.vue";
export default {
  components: {
    classTest,
  },
  props: {
    options: Object,
    pointData: "",
  },
  data() {
    return {
      qulity: [],
      videoCurrentTime: "",
      duration: "",
      timer: null,
      allTestTime: [],
      needScore: false,
      isFullScreen: false,
      cutid: this.$route.query.cutid,
      subtitles: [],
      currentSubtitle: 0, // 0为原文， 1为译文
    };
  },
  metgids: {},
  mounted() {
    this.$nextTick(() => {
      // 判断是否有学分要求，如果有学分限制的话后面会屏蔽手动修改进度
      this.needScore = this.options.need_score_status === true && !this.cutid;

      console.log(this.needScore);
      this.initDPlayer();
    });
  },

  methods: {
    initDPlayer() {
      console.log(this.options.subtitles1_path);
      this.qualityAll = [];
      this.showQuality();
      const hls = new Hls();
      const dp = {
        container: document.getElementById("dplayer"),
        //播放器的一些参数
        autoplay: true, //视频自动播放
        theme: "#FADFA3", //主题色
        loop: false, //视频循环播放
        lang: "zh-cn", //语言
        screenshot: true, //开启截图，如果开启，视频和视频封面需要允许跨域
        hotkey: !this.needScore, //开启热键，支持快进、快退、音量控制、播放暂停
        preload: "auto", //视频预加载，可选值: 'none', 'metadata', 'auto'
        // logo: require('logo.png'),                                     //左上角logo
        volume: 0.7, //默认音量，请注意播放器会记忆用户设置，用户手动设置音量后默认音量即失效
        mutex: true, //互斥，阻止多个播放器同时播放，当前播放器播放时暂停其他播放器
        playbackSpeed: [0.5, 0.75, 1, 1.25, 1.5, 2], //可选的播放速率，可以设置成自定义的数组
        video: {
          //视频信息
          url: this.options.pc_play_url, //视频链接
          type: "customHls", //可选值: 'auto', 'hls', 'flv', 'dash', 'webtorrent', 'normal' 或其他自定义类型, 见#MSE 支持
          customType: {
            customHls: function (video, player) {
              hls.loadSource(video.src);
              hls.attachMedia(video);
            },
          },
          pic: "dplayer.png", //视频封面
          // thumbnails: 'thumbnails.jpg',                                //视频缩略图，可以使用 DPlayer-thumbnails (opens new window)生成
          quality: this.qulity,
          defaultQuality: 0,
        },
        highlight: this.pointData, //高亮点（打点功能）
      };
      const player = new DPlayer(dp);
      this.player = player;

      player.on("quality_end", () => {
        this.getSubtitleCount();
      });
      player.on("loadedmetadata", () => {
        this.duration = player.video.duration;
      });

      this.getSubtitleCount();

      if (this.needScore) {
        // console.log("???");
        document.querySelector(".dplayer-bar-wrap").style = "display: none;";
      }

      this.getVideoTest(this.player);
    },
    getSubtitleCount() {
      //  根据后端返回的subtitle_path的有效数量进行处理
      this.subtitles = [
        {
          title: "原文",
          path: this.options.subtitles1_path,
        },
        {
          title: "译文",
          path: this.options.subtitles2_path,
        },
      ];
      if (this.options.subtitles1_path && this.options.subtitles2_path) {
        //  两个字幕路径同时存在
        this.setSubTitleBtn(this.subtitles[this.currentSubtitle]);
        this.setSubTitle(this.subtitles[this.currentSubtitle]);
      } else {
        if (this.options.subtitles1_path) {
          // 只存在原文
          this.setSubTitle(this.subtitles[0]);
        } else if (this.options.subtitles2_path) {
          //  只存在译文
          this.setSubtTitle(this.subtitles[1]);
        } else {
          // 都不存在
          return;
        }
      }
    },
    setSubTitleBtn(subTitle) {
      console.log("????????????!!!!!!!");
      // 两个字幕路径同时存在时，dplayer中显示当前字幕的dom，点击后切换字幕路径
      let oldDom = document.querySelector(".customer-subtitle-setting");
      if (oldDom) {
        oldDom.remove();
      }
      let rightBtnsDom = document.querySelector(".dplayer-icons-right");
      let newDom = document.createElement("div");
      var firstChild = rightBtnsDom.firstChild; //  父元素的子元素中的首元素
      newDom.innerHTML = subTitle.title;

      newDom.classList.add("dplayer-icon");
      newDom.classList.add("customer-subtitle-setting");
      rightBtnsDom.insertBefore(newDom, firstChild);

      //  给新生成的dom添加监听事件，点击后切换字幕和字幕按钮
      newDom.addEventListener("click", () => {
        this.currentSubtitle === 0
          ? (this.currentSubtitle = 1)
          : (this.currentSubtitle = 0);
        let subTitle = this.subtitles[this.currentSubtitle];
        this.setSubTitleBtn(subTitle);
        this.setSubTitle(subTitle);
      });
    },
    setSubTitle(subTitle) {
      let videoDom = document.querySelector("video");
      let trackDom = videoDom.querySelector("track");
      const addTrack = () => {
        let track = document.createElement("track");
        track.kind = "subtitles";
        track.src = this.BASE_URL + "/" + subTitle.path;
        track.default = true;
        this.player.video.appendChild(track);
      };
      if (trackDom) {
        videoDom.removeChild(trackDom);
        addTrack();
      } else {
        addTrack();
      }

      // if (subTitle.path) {
      //   let track = document.createElement("track");
      //   track.kind = "subtitles";
      //   track.src = this.BASE_URL + "/" + this.options.subtitles1_path;
      //   track.srclang = "en";
      //   track.default = true;
      //   this.player.video.appendChild(track);
      // }
    },
    showQuality() {
      let qualityAll = [
        //清晰度
        {
          name: "480P",
          url: this.options["480P"],
          type: "customHls",
        },
        {
          name: "720P",
          url: this.options["720P"],
          type: "customHls",
        },
        {
          name: "1080P",
          url: this.options["1080P"],
          type: "customHls",
        },
        {
          name: "原视频",
          url: this.options.pc_play_url,
          type: "customHls",
        },
      ];
      if (this.options["1080P"]) {
        this.qulity.push(qualityAll[2]);
      }
      if (this.options["720P"]) {
        this.qulity.push(qualityAll[1]);
      }
      if (this.options["480P"]) {
        this.qulity.push(qualityAll[0]);
      }
      if (this.qulity.length == 0) {
        this.qulity.push(qualityAll[3]);
      }
    },
    getVideoTest(player) {
      //测试点时弹出classTest
      this.allTestTime = this.$refs.classTest.allTestTime;
      let shakingFlag = 0;
      player.video.ontimeupdate = () => {
        this.videoCurrentTime = player.video.currentTime;
        this.$store.commit("SET_OPENCLASSTIME", this.videoCurrentTime);
        let videoCurrentTime = parseInt(this.videoCurrentTime);
        // 播放到测试时间节点，获取测试题目进行展示
        if (this.allTestTime.includes(videoCurrentTime)) {
          this.$refs.classTest.dplayerTest(videoCurrentTime);
          this.allTestTime = this.$refs.classTest.allTestTime;
        }
        if (this.duration && parseInt(this.duration) <= videoCurrentTime) {
          // 简单防抖
          if (shakingFlag === 0) {
            shakingFlag = 1;
            console.log("shakingFlag", shakingFlag);
            this.$refs.classTest.dplayerEnd();
          }
        }
      };
    },
    playVideo() {
      this.player.play();
    },
    pauseVideo() {
      this.player.pause();
    },
    fullScreen() {
      if (this.isFullScreen) {
        this.player.fullScreen.cancel("browser");
        this.isFullScreen = false;
      } else {
        this.player.fullScreen.request("browser");
        this.isFullScreen = true;
      }
    },
  },
};
</script>
<style scoped>
#dplayer /deep/ {
  height: 100%;
  /* overflow: visible; */
}

#dplayer /deep/ .dplayer-video-current {
  /* width: auto; */
  height: 100%;
  /* width: 1200px; */
  margin: 0px auto;
}
#dplayer /deep/ .dplayer-video-wrap {
  height: 100%;
  overflow: hidden;
}
#dplayer /deep/ .dplayer-video {
  height: 100%;
}
#playercontent {
  height: 100%;
}

#dplayer /deep/ .customer-subtitle-setting {
  display: inline-block;
  height: 100%;
  color: #d5d5d5;
  line-height: 22px;
  z-index: 2;
  position: relative;
}

/* dplayer /deep/ .dplayer-video-current {
  width: auto;
  height: 672px;
  margin: 0 auto;
} */

#dplayer /deep/ video::cue {
  color: white;
  text-shadow: 0 2px 2px #3e3b5b;
  background: rgba(73, 71, 101, 0);
}
#dplayer /deep/ video::cue(b) {
  color: red;
}
</style>